package main

import (
	"encoding/json"
	"fmt"
	"gitee.com/hlwqds/rabitmqTest/config"
	"gitee.com/hlwqds/rabitmqTest/log"
	"gitee.com/hlwqds/rabitmqTest/rabbitmqInAction/rpcServer/rpcConfig"
	"gitee.com/hlwqds/rabitmqTest/rabbitmqInAction/rpcServer/rpcMessage"
	"github.com/streadway/amqp"
)

func main(){
	conn, err := amqp.Dial(config.GenURLFromConfig())
	log.FailOnError(err, "amqp.Dial error")
	defer conn.Close()
	ch, err := conn.Channel()
	log.FailOnError(err, "conn.Channel error")
	defer ch.Close()

	ch.ExchangeDeclare(
		rpcConfig.RpcExchange,
		"direct",
		false,
		false,
		false,
		false,
		nil,
		)

	ch.QueueDeclare(
		rpcConfig.RpcQueuePing,
		false,
		false,
		false,
		false,
		nil)

	ch.QueueBind(
		rpcConfig.RpcQueuePing,
		"ping",
		rpcConfig.RpcExchange,
		false,
		nil)

	rpcCh, err := ch.Consume(
		rpcConfig.RpcQueuePing,
		"ping",
		false,
		false,
		false,
		false,
		nil,
		)
	var messStruct rpcMessage.Message
	for{
		data := <-rpcCh
		ch.Ack(data.DeliveryTag, false)
		json.Unmarshal(data.Body, &messStruct)
		fmt.Println("Received API call...replying...")
		ch.Publish(
			"",
			data.ReplyTo,
			false,
			false,
			amqp.Publishing{
				ContentType: "application/json",
				Body: []byte(fmt.Sprintf("Pong!%d", messStruct.Time)),
			})
	}
}